<template>
  <view class="qa-list-page">
    <!-- 搜索栏 -->
    <view class="search-section">
      <view class="search-box">
        <view class="search-input-box">
          <image src="/static/image/icon_search.png" class="search-icon" mode="aspectFit"></image>
          <input
            class="search-input"
            placeholder="搜索问题或答案"
            v-model="searchKeyword"
            @confirm="handleSearch"
            confirm-type="search"
          />
          <text class="search-btn" @click="handleSearch">搜索</text>
        </view>
      </view>

      <!-- 筛选栏 -->
      <view class="filter-bar">
        <view class="filter-item" :class="[currentFilter === 'all' ? 'active' : '']" @click="setFilter('all')">
          <text class="filter-text">全部</text>
        </view>
        <view class="filter-item" :class="[currentFilter === 'my' ? 'active' : '']" @click="setFilter('my')">
          <text class="filter-text">我的提问</text>
        </view>
      </view>
    </view>

    <!-- 问答列表 -->
    <view class="qa-list">
      <view class="qa-item" v-for="(item, index) in qaList" :key="index" @click="viewQaDetail(item)">
        <view class="qa-question">
          <view class="question-icon">
            <text class="question-text">问</text>
          </view>
          <view class="question-content">
            <text class="question-title">{{ item.question_content }}</text>
            <view class="question-meta">
              <text class="question-time">{{ formatTime(item.create_time) }}</text>
<!--              <text class="question-views">{{ item.view_count }}次浏览</text>-->
            </view>
          </view>
        </view>

        <!-- 如果有回答则显示回答 -->
        <view class="qa-answer" v-if="item.answer_content">
          <image src="/static/info/icon_answer.png" class="answer-avatar" mode="aspectFill"></image>
          <view class="answer-content">
            <text class="answer-text" :class="[item.isExpanded ? 'expanded' : '']">{{ item.answer_content }}</text>
            <text class="expand-btn" v-if="item.needExpand" @click.stop="expandAnswer(item)">
              {{ item.isExpanded ? '收起' : '展开 >' }}
            </text>
            <view class="answer-meta">
              <text class="answer-time">{{ formatTime(item.answer_time) }}</text>
              <text class="answer-handler">{{ item.handler }}</text>
            </view>
          </view>
        </view>

        <!-- 如果没有回答则显示状态 -->
        <view class="qa-status" v-else>
          <view class="status-tag" :class="[getStatusClass(item.status)]">
            <text class="status-text">{{ getStatusText(item.status) }}</text>
          </view>
        </view>
      </view>

      <!-- 加载更多 -->
      <view class="load-more" v-if="hasMore">
        <text class="load-text" @click="loadMore">加载更多</text>
      </view>

      <!-- 没有更多数据 -->
      <view class="no-more" v-else-if="qaList.length > 0">
        <text class="no-more-text">没有更多数据了</text>
      </view>

      <!-- 空状态 -->
      <view class="empty-state" v-if="qaList.length === 0 && !loading">
<!--        <image src="/static/image/no_permission.png" class="empty-icon" mode="aspectFit"></image>-->
        <text class="empty-text">{{ getEmptyText() }}</text>
      </view>
    </view>

    <!-- 悬浮提问按钮 -->
    <view class="float-ask-btn" @click="askQuestion">
      <image src="/static/info/icon_send.png" class="ask-icon" mode="aspectFit"></image>
    </view>

    <!-- 发布问题弹窗 -->
    <u-popup v-model="showAskPopup" mode="bottom" border-radius="32rpx 32rpx 0 0" height="60%">
      <view class="ask-popup">
        <view class="popup-header">
          <text class="popup-title">发布问题</text>
          <text class="popup-close" @click="closeAskPopup">×</text>
        </view>

        <view class="popup-content">
          <view class="input-section">
            <text class="input-label">问题内容</text>
            <textarea
              class="question-textarea"
              placeholder="请详细描述您的问题，这样我们才能更好地帮助您..."
              v-model="questionContent"
              maxlength="1000"
              show-confirm-bar="false"
              auto-height
            ></textarea>
            <view class="char-count">
              <text class="count-text">{{ questionContent.length }}/1000</text>
            </view>
          </view>
        </view>

        <view class="popup-footer">
          <button class="submit-btn" :disabled="!canSubmit" @click="submitQuestion">
            <text class="submit-text">发布问题</text>
          </button>
        </view>
      </view>
    </u-popup>
	</view>
</template>

<script>
import Navbar from "../../components/Navbar.vue";
import api from "../../config/api.js";

	export default {
  components: { Navbar },
		data() {
			return {
      // 搜索关键词
      searchKeyword: '',
      // 当前筛选条件
      currentFilter: 'all',
      // 问答列表
      qaList: [],
      // 分页参数
      page: 1,
      pageSize: 10,
      // 是否还有更多数据
      hasMore: false,
      // 是否正在加载
      loading: false,
      // 筛选参数
      filterParams: {
        all: {},
        my: {} // 我的提问，会在方法中动态添加user_id
      },

      // 发布问题相关
      showAskPopup: false,
      questionContent: '',
      contactInfo: '',
      selectedCategory: null,
      categoryOptions: [
        { value: 1, label: '技术问题' },
        { value: 2, label: '学习咨询' },
        { value: 3, label: '考试相关' },
        { value: 4, label: '就业指导' },
        { value: 5, label: '其他问题' }
      ]
    }
  },
  computed: {
    // 是否可以提交
    canSubmit() {
      return this.questionContent.trim().length >= 0
    }
  },
  onLoad(options) {
    // 如果有搜索关键词，设置搜索
    if (options.keyword) {
      this.searchKeyword = options.keyword;
      this.currentFilter = 'search';
    }

    // 加载问答列表
    this.loadQaList();
  },
  onPullDownRefresh() {
    this.refreshList();
  },
  onReachBottom() {
    if (this.hasMore && !this.loading) {
      this.loadMore();
			}
		},
  methods: {
    // 加载问答列表
    async loadQaList(isLoadMore = false) {
      if (this.loading) return;

      this.loading = true;

      try {
        const params = {
          pageNo: this.page,
          pageSize: this.pageSize,
          is_public: 1,
          question_content: this.searchKeyword
        };

        // 如果是"我的提问"，添加用户ID筛选
        if (this.currentFilter === 'my' && this.userInfo.id) {
          params.user_id = this.userInfo.id;
        }
        const result = await api.getQaPage(params);
        this.handleQaListResult(result, isLoadMore);
      } catch (error) {
        console.error('加载问答列表失败:', error);
        uni.showToast({
          title: '加载失败',
          icon: 'none'
        });
      } finally {
        this.loading = false;
        uni.stopPullDownRefresh();
      }
    },

    // 处理问答列表结果
    handleQaListResult(result, isLoadMore) {
      const list = result.list || [];

      // 处理每个问答项，添加展开状态
      const processedList = list.map(item => ({
        ...item,
        isExpanded: false,
        needExpand: item.answer_content && item.answer_content.length > 100,
        isLiked: false // 这里可以根据用户登录状态判断是否已点赞
      }));

      if (isLoadMore) {
        this.qaList = [...this.qaList, ...processedList];
      } else {
        this.qaList = processedList;
      }

      this.hasMore = this.qaList.length < result.total;
    },

    // 刷新列表
    refreshList() {
      this.page = 1;
      this.hasMore = true;
      this.loadQaList();
    },

    // 加载更多
    loadMore() {
      if (this.hasMore && !this.loading) {
        this.page++;
        this.loadQaList(true);
      }
    },

    // 搜索
    handleSearch() {
      if (this.searchKeyword.trim()) {
        this.currentFilter = 'search';
        this.refreshList();
      } else {
        this.currentFilter = 'all';
        this.refreshList();
      }
    },

    // 设置筛选条件
    setFilter(filter) {
      // 如果选择"我的提问"，检查用户登录状态
      if (filter === 'my') {
        if (!this.userInfo.id) {
          uni.showToast({
            title: '请先登录',
            icon: 'none'
          });
          return;
        }
      }

      this.currentFilter = filter;
      this.searchKeyword = '';
      this.refreshList();
    },

    // 展开/收起答案
    expandAnswer(item) {
      this.$set(item, 'isExpanded', !item.isExpanded);
    },

    // 查看问答详情
    viewQaDetail(item) {
      // 暂时显示提示，后续可以开发详情页面
      uni.showToast({
        title: '详情页面开发中',
        icon: 'none'
      });
    },

    // 点赞问答
    async likeQa(item) {
      try {
        await api.likeQa(item.id);
        this.$set(item, 'isLiked', !item.isLiked);
        this.$set(item, 'like_count', item.isLiked ? item.like_count + 1 : item.like_count - 1);
        uni.showToast({
          title: item.isLiked ? '点赞成功' : '取消点赞',
          icon: 'success'
        });
      } catch (error) {
        console.error('点赞失败:', error);
        uni.showToast({
          title: '操作失败',
          icon: 'none'
        });
      }
    },

    // 分享问答
    shareQa(item) {
      uni.showShareMenu({
        withShareTicket: true,
        menus: ['shareAppMessage', 'shareTimeline']
      });
    },

    // 提问
    askQuestion() {
      this.showAskPopup = true;
    },

    // 关闭提问弹窗
    closeAskPopup() {
      this.showAskPopup = false;
      this.resetForm();
    },

    // 重置表单
    resetForm() {
      this.questionContent = '';
      this.contactInfo = '';
      this.selectedCategory = null;
    },

    // 分类选择
    onCategoryChange(e) {
      const index = e.detail.value;
      this.selectedCategory = this.categoryOptions[index];
    },

    // 提交问题
    async submitQuestion() {
      if (!this.canSubmit) {
        uni.showToast({
          title: '问题内容不能为空',
          icon: 'none'
        });
        return;
      }

      try {
        uni.showLoading({
          title: '发布中...'
        })
        const questionData = {
          user_id: this.userInfo.id,
          question_content: this.questionContent.trim(),
          is_public: 0
        };
        await this.$api.createQa(questionData);
        uni.hideLoading()
        uni.showToast({
          title: '问题发布成功',
          icon: 'success'
        });

        this.closeAskPopup();

        // 刷新列表
        this.refreshList();

      } catch (error) {
        console.error('发布问题失败:', error);
        uni.showToast({
          title: '发布失败，请重试',
          icon: 'none'
        });
      }
    },

    // 格式化时间
    formatTime(time) {
      if (!time) return '';

      const now = new Date();
      const targetTime = new Date(time);
      const diff = now - targetTime;

      const minute = 60 * 1000;
      const hour = 60 * minute;
      const day = 24 * hour;
      const month = 30 * day;
      const year = 365 * day;

      if (diff < minute) {
        return '刚刚';
      } else if (diff < hour) {
        return Math.floor(diff / minute) + '分钟前';
      } else if (diff < day) {
        return Math.floor(diff / hour) + '小时前';
      } else if (diff < month) {
        return Math.floor(diff / day) + '天前';
      } else if (diff < year) {
        return Math.floor(diff / month) + '个月前';
      } else {
        return Math.floor(diff / year) + '年前';
      }
    },

    // 获取状态文本
    getStatusText(status) {
      const statusMap = {
        0: '待处理',
        1: '已回答',
        2: '已拒绝'
      };
      return statusMap[status] || '未知';
    },

    // 获取状态样式类
    getStatusClass(status) {
      const classMap = {
        0: 'status-pending',
        1: 'status-answered',
        2: 'status-rejected'
      };
      return classMap[status] || 'status-pending';
    },

    // 获取空状态文本
    getEmptyText() {
      if (this.currentFilter === 'my') {
        return '您还没有发布过问题';
      } else if (this.currentFilter === 'search') {
        return '没有找到相关问题';
      } else {
        return '暂无问答数据';
      }
    }
  },

  onShareAppMessage() {
    return {
      title: '问答专区 - 金仕咨询',
      path: '/pages/qa/qa'
    };
  },

  onShareTimeline() {
    return {
      title: '问答专区 - 金仕咨询'
    };
		}
	}
</script>

<style lang="scss">
.qa-list-page {
  min-height: 100vh;
  background-color: #f5f5f5;
  padding-bottom: 120rpx;

  // 搜索区域
  .search-section {
    background: #FFFFFF;
    padding: 24rpx;
    border-bottom: 1rpx solid #f0f0f0;

    .search-box {
      margin-bottom: 24rpx;

      .search-input-box {
        display: flex;
        align-items: center;
        background: #f8f8f8;
        border-radius: 32rpx;
        padding: 16rpx 24rpx;

        .search-icon {
          width: 32rpx;
          height: 32rpx;
          margin-right: 16rpx;
        }

        .search-input {
          flex: 1;
          font-size: 28rpx;
          color: #333333;
        }

        .search-btn {
          font-size: 28rpx;
          color: #539DF3;
          padding-left: 24rpx;
        }
      }
    }

    .filter-bar {
      display: flex;
      justify-content: space-around;

      .filter-item {
        padding: 12rpx 24rpx;
        border-radius: 24rpx;
        background: #f8f8f8;

        &.active {
          background: #539DF3;

          .filter-text {
            color: #FFFFFF;
          }
        }

        .filter-text {
          font-size: 26rpx;
          color: #666666;
        }
      }
    }
  }

  // 问答列表
  .qa-list {
    padding: 24rpx;

    .qa-item {
      background: #FFFFFF;
      border-radius: 16rpx;
      padding: 32rpx;
      margin-bottom: 24rpx;

      .qa-question {
        display: flex;
        align-items: flex-start;
        margin-bottom: 24rpx;

        .question-icon {
          width: 48rpx;
          height: 48rpx;
          background: #539DF3;
          border-radius: 50%;
          display: flex;
          align-items: center;
          justify-content: center;
          margin-right: 16rpx;
          flex-shrink: 0;

          .question-text {
            color: #FFFFFF;
            font-size: 28rpx;
            font-weight: bold;
          }
        }

        .question-content {
          flex: 1;

          .question-title {
            font-size: 30rpx;
            color: #333333;
            line-height: 1.4;
            margin-bottom: 12rpx;
            display: block;
          }

          .question-meta {
            display: flex;
            align-items: center;

            .question-time {
              font-size: 24rpx;
              color: #999999;
              margin-right: 24rpx;
            }

            .question-views {
              font-size: 24rpx;
              color: #999999;
            }
          }
        }
      }

      .qa-answer {
        display: flex;
        margin-bottom: 24rpx;

        .answer-avatar {
          width: 48rpx;
          height: 48rpx;
          border-radius: 24rpx;
          margin-right: 16rpx;
          flex-shrink: 0;
        }

        .answer-content {
          flex: 1;

          .answer-text {
            font-size: 28rpx;
            color: #666666;
            line-height: 1.4;
            display: block;
            overflow: hidden;
            text-overflow: ellipsis;
            display: -webkit-box;
            -webkit-line-clamp: 2;
            -webkit-box-orient: vertical;

            &.expanded {
              -webkit-line-clamp: unset;
              display: block;
            }
          }

          .expand-btn {
            font-size: 26rpx;
            color: #539DF3;
            text-align: right;
            width: 100%;
            display: block;
            margin-top: 8rpx;
          }

          .answer-meta {
            display: flex;
            align-items: center;
            margin-top: 12rpx;

            .answer-time {
              font-size: 24rpx;
              color: #999999;
              margin-right: 24rpx;
            }

            .answer-handler {
              font-size: 24rpx;
              color: #539DF3;
            }
          }
        }
      }

      .qa-status {
        margin-bottom: 24rpx;

        .status-tag {
          display: inline-block;
          padding: 8rpx 16rpx;
          border-radius: 16rpx;
          font-size: 24rpx;

          &.status-pending {
            background: #fff7e6;
            color: #fa8c16;
          }

          &.status-answered {
            background: #f6ffed;
            color: #52c41a;
          }

          &.status-rejected {
            background: #fff2f0;
            color: #ff4d4f;
          }
        }
      }

      .qa-actions {
        display: flex;
        justify-content: flex-end;
        align-items: center;
        border-top: 1rpx solid #f0f0f0;
        padding-top: 24rpx;

        .action-item {
          display: flex;
          align-items: center;
          margin-left: 32rpx;

          .action-icon {
            width: 32rpx;
            height: 32rpx;
            margin-right: 8rpx;
          }

          .action-text {
            font-size: 26rpx;
            color: #666666;
          }
        }
      }
    }

    .load-more {
      text-align: center;
      padding: 32rpx 0;

      .load-text {
        font-size: 28rpx;
        color: #539DF3;
      }
    }

    .no-more {
      text-align: center;
      padding: 32rpx 0;

      .no-more-text {
        font-size: 26rpx;
        color: #999999;
      }
    }

    .empty-state {
      text-align: center;
      padding: 120rpx 0;

      .empty-icon {
        width: 200rpx;
        height: 200rpx;
        margin-bottom: 32rpx;
      }

      .empty-text {
        font-size: 28rpx;
        color: #999999;
      }
    }
  }

  // 悬浮提问按钮
  .float-ask-btn {
    position: fixed;
    right: 32rpx;
    bottom: 120rpx;
    width: 100rpx;
    height: 100rpx;
    background: #539DF3;
    border-radius: 50%;
    display: flex;
    align-items: center;
    justify-content: center;
    box-shadow: 0 8rpx 24rpx rgba(83, 157, 243, 0.3);
    z-index: 999;

    .ask-icon {
      width: 48rpx;
      height: 48rpx;
    }
  }

  // 发布问题弹窗样式
  .ask-popup {
    height: 100%;
    display: flex;
    flex-direction: column;

    .popup-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      padding: 32rpx;
      border-bottom: 1rpx solid #f0f0f0;

      .popup-title {
        font-size: 32rpx;
        font-weight: bold;
        color: #333333;
      }

      .popup-close {
        font-size: 48rpx;
        color: #999999;
        line-height: 1;
        padding: 8rpx;
      }
    }

    .popup-content {
      flex: 1;
      padding: 32rpx;
      overflow-y: auto;

      .input-section {
        margin-bottom: 32rpx;

        .input-label {
          font-size: 28rpx;
          color: #333333;
          margin-bottom: 16rpx;
          display: block;
        }

        .question-textarea {
          width: 100%;
          min-height: 500rpx;
          padding: 24rpx;
          background: #f8f8f8;
          border-radius: 16rpx;
          font-size: 28rpx;
          color: #333333;
          line-height: 1.5;
          border: none;
          box-sizing: border-box;
        }

        .char-count {
          text-align: right;
          margin-top: 12rpx;

          .count-text {
            font-size: 24rpx;
            color: #999999;
          }
        }

        .contact-input {
          width: 100%;
          height: 80rpx;
          padding: 0 24rpx;
          background: #f8f8f8;
          border-radius: 16rpx;
          font-size: 28rpx;
          color: #333333;
          border: none;
          box-sizing: border-box;
        }

        .picker-box {
          display: flex;
          justify-content: space-between;
          align-items: center;
          height: 80rpx;
          padding: 0 24rpx;
          background: #f8f8f8;
          border-radius: 16rpx;

          .picker-text {
            font-size: 28rpx;
            color: #333333;

            &.placeholder {
              color: #999999;
            }
          }

          .picker-arrow {
            width: 24rpx;
            height: 24rpx;
          }
        }
      }
    }

    .popup-footer {
      padding: 32rpx;
      border-top: 1rpx solid #f0f0f0;

      .submit-btn {
        width: 100%;
        height: 88rpx;
        background: #539DF3;
        border-radius: 16rpx;
        border: none;
        display: flex;
        align-items: center;
        justify-content: center;

        &:disabled {
          background: #cccccc;
        }

        .submit-text {
          font-size: 32rpx;
          color: #FFFFFF;
          //font-weight: bold;
        }
      }
    }
  }
}
</style>
